package dbdata

import (
	"reflect"
	"github.com/astaxie/beego/orm"
	"fmt"
	"cloud_worm/util/umodels/mysqldb"
)

const (
	WeaponAlertOK = 1
	WeaponAlertFailed = 0
)

type WeaponAlertLog struct {
	Id          int64
	WormId 		string
	WeaponId    int64
	TaskId      string

	OptionId    int
	OptionName  string
	Result      int
	AlertMsg    string

	Created     int64
	Updated     int64
	Status      int
}

func (w *WeaponAlertLog) TableName() string {
	return reflect.TypeOf(*w).Name()
}

func (w *WeaponAlertLog) Read(fields ...string) error {
	err := orm.NewOrm().Read(w, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func (w *WeaponAlertLog) Update(fields ...string) error {
	_, err := orm.NewOrm().Update(w, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}
	return nil
}

func (w *WeaponAlertLog) Insert() error {
	_, err := orm.NewOrm().Insert(w)
	if err != nil {
		return fmt.Errorf("%s, %s", w.TableName(), err.Error())
	}

	return nil
}

func init()  {
	orm.RegisterModel(new(WeaponAlertLog))
}

func (w *WeaponAlertLog) SelectForReport(offset int, limit int, taskId string, result int) ([]*WeaponAlertLog, error) {
	var alertLogs []*WeaponAlertLog

	qs := orm.NewOrm().QueryTable(w).Offset(offset).Limit(limit)
	if taskId != mysqldb.SelectStrAll {
		qs = qs.Filter("task_id", taskId)
	}
	if result != mysqldb.SelectIntAll {
		qs = qs.Filter("result", result)
	}

	_, err := qs.All(&alertLogs)
	if err != nil {
		return nil, err
	}

	return alertLogs, nil
}

func (w *WeaponAlertLog) Select(offset int, limit int, wormId string, weaponId int64, taskId string) ([]*WeaponAlertLog, error) {
	var alertLogs []*WeaponAlertLog

	qs := orm.NewOrm().QueryTable(w).Offset(offset).Limit(limit)

	if wormId != mysqldb.SelectStrAll {
		qs = qs.Filter("worm_id", wormId)
	}
	if weaponId != mysqldb.SelectIntAll {
		qs = qs.Filter("weapon_id", weaponId)
	}
	if taskId != mysqldb.SelectStrAll {
		qs = qs.Filter("task_id", taskId)
	}

	_, err := qs.All(&alertLogs)
	if err != nil {
		return nil, err
	}

	return alertLogs, nil
}